using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Data;
using Models;
using Services;
using Constants;

// 创建WebApplication构建器
var builder = WebApplication.CreateBuilder(args);

/// <summary>
/// 服务配置部分
/// </summary>

// 添加MVC控制器
builder.Services.AddControllers();
// 添加API文档支持
builder.Services.AddEndpointsApiExplorer();
// 添加Swagger支持
builder.Services.AddSwaggerGen();

// 配置数据库上下文
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

// 配置Identity身份认证
builder.Services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
    // 密码策略配置
    options.Password.RequireDigit = true;         // 要求包含数字
    options.Password.RequireLowercase = true;     // 要求包含小写字母
    options.Password.RequireUppercase = true;     // 要求包含大写字母
    options.Password.RequireNonAlphanumeric = true; // 要求包含特殊字符
    options.Password.RequiredLength = 8;          // 最小密码长度
})
.AddEntityFrameworkStores<ApplicationDbContext>()  // 使用EF Core存储
.AddDefaultTokenProviders();                      // 添加默认令牌提供程序

// 配置JWT认证
builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    // 获取JWT密钥配置
    var jwtKey = builder.Configuration["JwtSettings:SecretKey"] ??
        throw new InvalidOperationException("JWT SecretKey is not configured");

    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,           // 验证颁发者
        ValidateAudience = true,         // 验证接收者
        ValidateLifetime = true,         // 验证过期时间
        ValidateIssuerSigningKey = true, // 验证签名
        ValidIssuer = builder.Configuration["JwtSettings:Issuer"],
        ValidAudience = builder.Configuration["JwtSettings:Audience"],
        IssuerSigningKey = new SymmetricSecurityKey(
            Encoding.UTF8.GetBytes(jwtKey))
    };
});

// 配置授权策略
builder.Services.AddAuthorization(options =>
{
    // 添加基于角色的策略
    options.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));
    options.AddPolicy("RequireUserRole", policy => policy.RequireRole("User"));
});

// 配置邮件服务
builder.Services.Configure<EmailSettings>(builder.Configuration.GetSection("EmailSettings"));
builder.Services.AddScoped<IEmailSender, SmtpEmailSender>();

// 配置细粒度的权限策略
builder.Services.AddAuthorization(options =>
{
    // 为每种操作类型添加权限策略
    foreach (PermissionOperations operation in Enum.GetValues(typeof(PermissionOperations)))
    {
        // 用户管理权限策略
        options.AddPolicy(
            $"{PermissionConstants.UsersPrefix}{operation}",
            policy => policy.RequireClaim("Permission", $"{PermissionConstants.UsersPrefix}{operation}"));

        // 角色管理权限策略
        options.AddPolicy(
            $"{PermissionConstants.RolesPrefix}{operation}",
            policy => policy.RequireClaim("Permission", $"{PermissionConstants.RolesPrefix}{operation}"));
    }
});

// 注册权限服务
builder.Services.AddScoped<IPermissionService, PermissionService>();

// 添加内存缓存服务
builder.Services.AddMemoryCache();
builder.Services.AddScoped<ICacheService, MemoryCacheService>();

/// <summary>
/// 应用程序配置部分
/// </summary>
var app = builder.Build();

// 初始化数据库
using (var scope = app.Services.CreateScope())
{
    await DbInitializer.Initialize(scope.ServiceProvider);
}

// 配置HTTP请求处理管道
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();        // 启用Swagger
    app.UseSwaggerUI();      // 启用SwaggerUI
}

app.UseHttpsRedirection();   // 启用HTTPS重定向

// 添加认证和授权中间件
app.UseAuthentication();     // 启用身份认证
app.UseAuthorization();      // 启用授权

app.MapControllers();        // 映射控制器路由

// 启动应用程序
app.Run();
